package com.ncui.wisdomLearn.biz.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ncui.wisdomLearn.api.entity.UserRole;
import com.ncui.wisdomLearn.biz.user.mapper.UserRoleMapper;
import com.ncui.wisdomLearn.biz.user.service.UserRoleService;
import com.ncui.wisdomLearn.common.exception.ParamException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户角色表(UserRole)表 服务实现类
 *
 * @author lvlele
 * @since 2025-01-04 01:06:10
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    @Override
    public List<Long> getRoleIdsByUserId(Long userId) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId, userId);
        return list(wrapper).stream()
                .map(UserRole::getRoleId)
                .toList();
    }

    @Override
    public List<Long> getUserIdsByRoleId(Long roleId) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getRoleId, roleId);
        return list(wrapper).stream()
                .map(UserRole::getUserId)
                .toList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addUserRole(Long userId, Long roleId) {
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(roleId);
        return save(userRole);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUserRole(Long userId, Long roleId) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId, userId)
                .eq(UserRole::getRoleId, roleId);
        return remove(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteUserRole(List<UserRole> userRoleList) {
        if (userRoleList == null || userRoleList.isEmpty()) {
            throw new ParamException("用户或角色不能为空");
        }
        return removeByIds(userRoleList);
    }
}

